<template>
  <div id="qiItemSetDiv">
    <el-container style="height: 100%; width: 100%">
      <Splitpanes>
        <Pane size="15">
          <el-aside style="width: 100%">
            <el-tabs tab-position="left" type="card" v-model="activeName" @tab-click="tabMajorClick" class="leftTabs">
              <el-tab-pane v-for="(item, index) in qiIndexMajorList" :key="index" :label="item.majorName" :name="item.id" lazy></el-tab-pane>
            </el-tabs>
          </el-aside>
        </Pane>
        <Pane size="85">
          <el-main style="height: 100%">
            <el-form ref="qiIndexSqlFormRef" style="height: 100%" :model="qiIndexSqlForm" :rules="qiIndexSqlFormRule" label-width="100px" inline-message>
              <Splitpanes horizontal class="horizontalLine">
                <Pane size="5">
                  <vxe-toolbar perfect>
                    <template #buttons>
                      <div class="smallToolTitle">数据源配置</div>
                      <vxe-select v-model="qiIndexSqlForm.qiDatabaseId" :filterable="true" @change="databaseChangeEvent" transfer clearable>
                        <vxe-option v-for="qiDatabase in qiDatabaseList" :key="qiDatabase.id" :value="qiDatabase.id" :label="qiDatabase.databaseName"></vxe-option>
                      </vxe-select>
                      <vxe-button class="button-blue toolbartitle3" icon="vxe-icon-setting-fill" @click="addQiDatabaseModal"></vxe-button>
                      <vxe-button type="text" class="button-blue toolbartitle2" icon="vxe-icon-copy" content="复制" @click="copyQiIndexSqlClick" :disabled="IsEmpty(qiIndexSqlForm.id)"></vxe-button>
                      <vxe-button type="text" class="button-blue toolbartitle2" icon="vxe-icon-paste" content="粘贴" @click="pasteQiIndexSqlClick" :disabled="IsEmpty(copyQiIndexSql.id)"></vxe-button>
                      <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleQiIndexSqlDelete" :disabled="IsEmpty(qiIndexSqlForm.id)"></vxe-button>
                      <div class="smallToolTitle">执行日期：</div>
                      <vxe-input v-model="searchForm.executeTime" placeholder="选择日期" type="date" valueFormat="yyyy-MM-dd" transfer></vxe-input>
                      <vxe-button type="text" :loading="execloading" class="button-blue toolbartitle2" icon="vxe-icon-send" content="立即执行" @click="executeImmediatelyClick" :disabled="IsEmpty(databaseTableList) || databaseTableList.length == 0"></vxe-button>

                    </template>
                  </vxe-toolbar>

                </Pane>
                <Pane size="95">
                  <Splitpanes horizontal>
                    <Pane size="50">
                      <el-tabs type="border-card" style="height: 100%" v-model="activeTableName" @tab-click="tabHandleClick">
                        <el-tab-pane label="相关表" name="TABLE">
                          <Splitpanes horizontal>
                            <Pane size="32">
                              <vxe-toolbar perfect>
                                <template #buttons>
                                  <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="添加查询表" @click="handleTableAdd()" :disabled="IsEmpty(databaseTableList) || databaseTableList.length == 0"></vxe-button>
                                </template>
                              </vxe-toolbar>
                              <div class="tablebox">
                                <vxe-table class="mytable-scrollbar" align="left" border="inner" ref="functionTableRef" height="auto" :row-config="{ isCurrent: true, isHover: true }" :loading="showLoading" :tree-config="{}" :column-config="{ resizable: true }" :data="qiIndexSqlForm.qiIndexSqlTableList" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" @current-change="tableRowClick" resizable show-overflow keep-source>
                                  <vxe-column field="tableName" title="表名" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                    <template #edit="{ row }">
                                      <vxe-select v-model="row.tableName" placeholder="请选择数据库表" clearable :filterable="true" transfer @change="tableNameChange">
                                        <vxe-option v-for="resultSign in databaseTableList" :key="resultSign" :label="resultSign" :value="resultSign"></vxe-option>
                                      </vxe-select>
                                    </template>
                                  </vxe-column>
                                  <vxe-column field="alias" title="别名" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                    <template #edit="{ row }">
                                      <vxe-input v-model="row.alias" type="text"></vxe-input>
                                    </template>
                                  </vxe-column>
                                  <vxe-column field="joinType" title="关联方式" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                    <template #edit="{ row }">
                                      <vxe-select v-model="row.joinType" placeholder="请选择关联方式" clearable transfer>
                                        <vxe-option v-for="resultSign in joinList" :key="resultSign.value" :label="resultSign.name" :value="resultSign.value"></vxe-option>
                                      </vxe-select>
                                    </template>
                                  </vxe-column>
                                  <vxe-column title="操作" fixed="right">
                                    <template #default="{ row }">
                                      <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="deleteSqlTable(row)" class="spanIcon"></vxe-button>
                                    </template>
                                  </vxe-column>
                                </vxe-table>
                              </div>
                            </Pane>
                            <Pane size="38">
                              <el-tabs type="border-card" v-model="activeSQLName" @tab-click="tabSQLClick" class="elTabsFour">
                                <el-tab-pane label="输出内容" name="SELECT">
                                  <vxe-toolbar perfect>
                                    <template #buttons>
                                      <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建SELECT" @click="addJoinSelect()" :disabled="IsEmpty(qiIndexSqlForm.qiIndexSqlTableList) || qiIndexSqlForm.qiIndexSqlTableList.length == 0"></vxe-button>
                                      <div class="saveBtn">
                                        <vxe-checkbox v-model="qiIndexSqlForm.distinctFlag" size="small" content="DISTINCT" :disabled="IsEmpty(qiIndexSqlForm.qiIndexSqlTableList) || qiIndexSqlForm.qiIndexSqlTableList.length == 0"></vxe-checkbox>
                                      </div>
                                    </template>
                                  </vxe-toolbar>
                                  <div class="tablebox">
                                    <vxe-table class="mytable-scrollbar" align="left" border="inner" ref="joinSelectTable" height="auto" :row-config="{ isCurrent: true, isHover: true }" :tree-config="{}" :column-config="{ resizable: true }" :data="qiIndexSqlForm.qiIndexSqlSelectList" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow keep-source>
                                      <vxe-column field="aggregation" title="聚合函数" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" width="100px" align="left">
                                        <template #edit="{ row }">
                                          <vxe-select v-model="row.aggregation" placeholder="请选择聚合函数" clearable transfer>
                                            <vxe-option v-for="aggregatObj in aggregationList" :key="aggregatObj.value" :label="aggregatObj.value" :value="aggregatObj.value"></vxe-option>
                                          </vxe-select>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="tableField" title="出参" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                        <template #edit="{ data, rowIndex }">
                                          <vxe-pulldown style="width: 100%; height: 100%" ref="pulldownRef" destroy-on-close transfer>
                                            <template #default>
                                              <vxe-input v-model="data.tableField" placeholder="请选择出参" @focus="(value) => focusEvent(value, rowIndex)" @change="(row) => changeEvent(row, data, rowIndex, 'tableField')"></vxe-input>
                                            </template>
                                            <template #dropdown>
                                              <vxe-table :row-config="{
                                                  isCurrent: true,
                                                  isHover: true,
                                                  keyField: 'id'
                                                }" class="mytable-scrollbar" height="300px" @current-change="(row) => tableFieldRowClick(row, data, rowIndex, 'tableField')" border="inner" ref="tableRef" :column-config="{ resizable: true }" :show-header="false" :tree-config="{ transform: true, rowField: 'label', parentField: 'pLabel', expandAll: true }" :data="fieldListByTable">
                                                <vxe-column field="label" title="label" tree-node></vxe-column>
                                              </vxe-table>
                                            </template>
                                          </vxe-pulldown>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="alias" title="别名" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                        <template #edit="{ row }">
                                          <vxe-input v-model="row.alias" type="text"></vxe-input>
                                        </template>
                                      </vxe-column>
                                      <vxe-column title="操作" fixed="right">
                                        <template #default="{ row }">
                                          <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="deleteSqlSelect(row)" class="spanIcon"></vxe-button>
                                        </template>
                                      </vxe-column>
                                    </vxe-table>
                                  </div>
                                </el-tab-pane>
                                <el-tab-pane label="相关表关系" name="ON">
                                  <vxe-toolbar perfect>
                                    <template #buttons>
                                      <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建On" @click="addJoinOn()" :disabled="IsEmpty(qiIndexSqlForm.qiIndexSqlTableList) || qiIndexSqlForm.qiIndexSqlTableList.length == 0"></vxe-button>
                                    </template>
                                  </vxe-toolbar>
                                  <div class="tablebox">
                                    <vxe-table :data="curIndex >= 0 && qiIndexSqlForm.qiIndexSqlTableList.length > 0 ? qiIndexSqlForm.qiIndexSqlTableList[curIndex].qiIndexSqlOnList : []" class="mytable-scrollbar" align="left" border="inner" ref="joinOnTable" height="auto" :row-config="{ isCurrent: true, isHover: true }" :tree-config="{}" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow keep-source>
                                      <vxe-column field="leftBracket" title="左括号" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                        <template #edit="{ row }">
                                          <vxe-input v-model="row.leftBracket" type="text"></vxe-input>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="leftParam" title="左参数" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" width="200px" align="left">
                                        <template #edit="{ data, rowIndex }">
                                          <vxe-pulldown style="width: 100%; height: 100%" ref="pulldownRef" destroy-on-close transfer>
                                            <template #default>
                                              <vxe-input v-model="data.leftParam" placeholder="请选择出参" @focus="(value) => focusEvent(value, rowIndex)" @change="(row) => changeEvent(row, data, rowIndex, 'leftParam')"></vxe-input>
                                            </template>
                                            <template #dropdown>
                                              <vxe-table :row-config="{
                                                  isCurrent: true,
                                                  isHover: true,
                                                  keyField: 'id'
                                                }" class="mytable-scrollbar" height="300px" @current-change="(row) => tableFieldRowClick(row, data, rowIndex, 'leftParam')" border="inner" ref="tableRef" :column-config="{ resizable: true }" :show-header="false" :tree-config="{ transform: true, rowField: 'label', parentField: 'pLabel', expandAll: true }" :data="fieldListByTable">
                                                <vxe-column field="label" title="label" tree-node></vxe-column>
                                              </vxe-table>
                                            </template>
                                          </vxe-pulldown>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="symbol" title="条件" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                        <template #edit="{ row }">
                                          <vxe-select v-model="row.symbol" placeholder="请选择关联方式" clearable transfer>
                                            <vxe-option v-for="resultSign in symbolList" :key="resultSign.value" :label="resultSign.value" :value="resultSign.value"></vxe-option>
                                          </vxe-select>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="rightParam" title="右参数" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" width="200px" align="left">
                                        <template #edit="{ data, rowIndex }">
                                          <!-- <vxe-select v-model="row.leftParam" placeholder="请选择左参数" :filterable="true" clearable transfer :option-groups="fieldListByTable"> </vxe-select> -->
                                          <vxe-pulldown style="width: 100%; height: 100%" ref="pulldownRef" destroy-on-close transfer>
                                            <template #default>
                                              <vxe-input v-model="data.rightParam" placeholder="请选择出参" @focus="(value) => focusEvent(value, rowIndex)" @change="(row) => changeEvent(row, data, rowIndex, 'rightParam')"></vxe-input>
                                            </template>
                                            <template #dropdown>
                                              <vxe-table :row-config="{
                                                  isCurrent: true,
                                                  isHover: true,
                                                  keyField: 'id'
                                                }" class="mytable-scrollbar" height="300px" @current-change="(row) => tableFieldRowClick(row, data, rowIndex, 'rightParam')" border="inner" ref="tableRef" :column-config="{ resizable: true }" :show-header="false" :tree-config="{ transform: true, rowField: 'label', parentField: 'pLabel', expandAll: true }" :data="fieldListByTable">
                                                <vxe-column field="label" title="label" tree-node></vxe-column>
                                              </vxe-table>
                                            </template>
                                          </vxe-pulldown>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="rightBracket" title="右括号" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                        <template #edit="{ row }">
                                          <vxe-input v-model="row.rightBracket" type="text"></vxe-input>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="relation" title="关联" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                        <template #edit="{ row }">
                                          <vxe-select v-model="row.relation" placeholder="请选择关联方式" clearable transfer>
                                            <vxe-option v-for="resultSign in relationList" :key="resultSign.value" :label="resultSign.value" :value="resultSign.value"></vxe-option>
                                          </vxe-select>
                                        </template>
                                      </vxe-column>
                                      <vxe-column title="操作" fixed="right">
                                        <template #default="{ row }">
                                          <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="deleteSqlOn(row)" class="spanIcon"></vxe-button>
                                        </template>
                                      </vxe-column>
                                    </vxe-table>
                                  </div>
                                </el-tab-pane>
                                <el-tab-pane label="查询条件" name="WHERE">
                                  <vxe-toolbar perfect>
                                    <template #buttons>
                                      <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建Where" @click="addJoinWhere()" :disabled="IsEmpty(qiIndexSqlForm.qiIndexSqlTableList) || qiIndexSqlForm.qiIndexSqlTableList.length == 0"></vxe-button>
                                    </template>
                                  </vxe-toolbar>
                                  <div class="tablebox">
                                    <vxe-table class="mytable-scrollbar" align="left" border="inner" ref="joinWhereTable" height="auto" :row-config="{ isCurrent: true, isHover: true }" :tree-config="{}" :column-config="{ resizable: true }" :data="qiIndexSqlForm.qiIndexSqlWhereList" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow keep-source>
                                      <vxe-column field="leftBracket" title="左括号" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                        <template #edit="{ row }">
                                          <vxe-input v-model="row.leftBracket" type="text"></vxe-input>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="leftParam" title="左参数" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" width="200px" align="left">
                                        <template #edit="{ data, rowIndex }">
                                          <vxe-pulldown style="width: 100%; height: 100%" ref="pulldownRef" destroy-on-close transfer>
                                            <template #default>
                                              <vxe-input v-model="data.leftParam" placeholder="请选择出参" @focus="(value) => focusEvent(value, rowIndex)" @change="(row) => changeEvent(row, data, rowIndex, 'leftParam')"></vxe-input>
                                            </template>
                                            <template #dropdown>
                                              <vxe-table :row-config="{
                                                  isCurrent: true,
                                                  isHover: true,
                                                  keyField: 'id'
                                                }" class="mytable-scrollbar" height="300px" @current-change="(row) => tableFieldRowClick(row, data, rowIndex, 'leftParam')" border="inner" ref="tableRef" :column-config="{ resizable: true }" :show-header="false" :tree-config="{ transform: true, rowField: 'label', parentField: 'pLabel', expandAll: true }" :data="fieldListByTable">
                                                <vxe-column field="label" title="label" tree-node></vxe-column>
                                              </vxe-table>
                                            </template>
                                          </vxe-pulldown>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="symbol" title="条件" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                        <template #edit="{ row }">
                                          <vxe-select v-model="row.symbol" placeholder="请选择关联方式" clearable transfer>
                                            <vxe-option v-for="resultSign in symbolList" :key="resultSign.value" :label="resultSign.value" :value="resultSign.value"></vxe-option>
                                          </vxe-select>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="rightParam" title="右参数" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" width="200px" align="left">
                                        <template #edit="{ data, rowIndex }">
                                          <vxe-pulldown style="width: 100%; height: 100%" ref="pulldownRef" destroy-on-close transfer>
                                            <template #default>
                                              <vxe-input v-model="data.rightParam" placeholder="请选择出参" @focus="(value) => focusEvent(value, rowIndex)" @change="(row) => changeEvent(row, data, rowIndex, 'rightParam')"></vxe-input>
                                            </template>
                                            <template #dropdown>
                                              <vxe-table :row-config="{
                                                  isCurrent: true,
                                                  isHover: true,
                                                  keyField: 'id'
                                                }" class="mytable-scrollbar" height="300px" @current-change="(row) => tableFieldRowClick(row, data, rowIndex, 'rightParam')" border="inner" ref="tableRef" :column-config="{ resizable: true }" :show-header="false" :tree-config="{ transform: true, rowField: 'label', parentField: 'pLabel', expandAll: true }" :data="fieldListByTable">
                                                <vxe-column field="label" title="label" tree-node></vxe-column>
                                              </vxe-table>
                                            </template>
                                          </vxe-pulldown>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="rightBracket" title="右括号" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                        <template #edit="{ row }">
                                          <vxe-input v-model="row.rightBracket" type="text"></vxe-input>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="relation" title="关联" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                        <template #edit="{ row }">
                                          <vxe-select v-model="row.relation" placeholder="请选择关联方式" clearable transfer>
                                            <vxe-option v-for="resultSign in relationList" :key="resultSign.value" :label="resultSign.value" :value="resultSign.value"></vxe-option>
                                          </vxe-select>
                                        </template>
                                      </vxe-column>
                                      <vxe-column title="操作" fixed="right">
                                        <template #default="{ row }">
                                          <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="deleteSqlWhere(row)" class="spanIcon"></vxe-button>
                                        </template>
                                      </vxe-column>
                                    </vxe-table>
                                  </div>
                                </el-tab-pane>
                                <el-tab-pane label="业务对照" name="EXISTS">
                                  <vxe-toolbar perfect>
                                    <template #buttons>
                                      <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建Exists" @click="addJoinExists()" :disabled="IsEmpty(qiIndexSqlForm.qiIndexSqlTableList) || qiIndexSqlForm.qiIndexSqlTableList.length == 0"></vxe-button>
                                    </template>
                                  </vxe-toolbar>
                                  <div class="tablebox">
                                    <vxe-table ref="joinExistsTable" :data="qiIndexSqlForm.qiIndexSqlExistsList" class="mytable-scrollbar" align="left" border="inner" height="auto" :row-config="{ isCurrent: true, isHover: true }" :tree-config="{}" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow keep-source>
                                      <vxe-column field="relation" title="关联" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                        <template #edit="{ row }">
                                          <vxe-select v-model="row.relation" placeholder="请选择关联方式" clearable transfer>
                                            <vxe-option v-for="resultSign in relationList" :key="resultSign.value" :label="resultSign.value" :value="resultSign.value"></vxe-option>
                                          </vxe-select>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="existsType" title="是否包含" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                        <template #edit="{ row }">
                                          <vxe-select v-model="row.existsType" placeholder="请选择是否包含" clearable transfer>
                                            <vxe-option v-for="existsTypeOBJ in existsTypeOBJList" :key="existsTypeOBJ.value" :label="existsTypeOBJ.value" :value="existsTypeOBJ.value"></vxe-option>
                                          </vxe-select>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="moduleType" title="业务编码" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                        <template #default="{ row }">
                                          <span>{{ getBusinessModuleDes(row) }}</span>
                                        </template>
                                        <template #edit="{ row }">
                                          <vxe-select v-model="row.moduleType" :filterable="false" placeholder="请选择业务编码" clearable transfer>
                                            <vxe-option v-for="bMObj in businessModuleList" :key="bMObj.id" :value="bMObj.moduleType" :label="bMObj.moduleName"></vxe-option>
                                          </vxe-select>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="rightParam" title="右参数" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" align="left">
                                        <template #edit="{ data, rowIndex }">
                                          <vxe-pulldown style="width: 100%; height: 100%" ref="pulldownRef" destroy-on-close transfer>
                                            <template #default>
                                              <vxe-input v-model="data.rightParam" placeholder="请选择出参" @focus="(value) => focusEvent(value, rowIndex)" @change="(row) => changeEvent(row, data, rowIndex, 'rightParam')"></vxe-input>
                                            </template>
                                            <template #dropdown>
                                              <vxe-table :row-config="{
                                                  isCurrent: true,
                                                  isHover: true,
                                                  keyField: 'id'
                                                }" class="mytable-scrollbar" height="300px" @current-change="(row) => tableFieldRowClick(row, data, rowIndex, 'rightParam')" border="inner" ref="tableRef" :column-config="{ resizable: true }" :show-header="false" :tree-config="{ transform: true, rowField: 'label', parentField: 'pLabel', expandAll: true }" :data="fieldListByTable">
                                                <vxe-column field="label" title="label" tree-node></vxe-column>
                                              </vxe-table>
                                            </template>
                                          </vxe-pulldown>
                                        </template>
                                      </vxe-column>
                                      <vxe-column title="操作" fixed="right">
                                        <template #default="{ row }">
                                          <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="deleteSqlExists(row)" class="spanIcon"></vxe-button>
                                        </template>
                                      </vxe-column>
                                    </vxe-table>
                                  </div>
                                </el-tab-pane>
                                <el-tab-pane label="指定日期" name="SPECIFY">
                                  <vxe-toolbar perfect>
                                    <template #buttons>
                                      <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建日期查询" @click="addJoinSpecify()" :disabled="IsEmpty(qiIndexSqlForm.qiIndexSqlTableList) || qiIndexSqlForm.qiIndexSqlTableList.length == 0"></vxe-button>
                                    </template>
                                  </vxe-toolbar>
                                  <div class="tablebox">
                                    <vxe-table class="mytable-scrollbar" align="left" border="inner" ref="joinSpecifyTable" height="auto" :row-config="{ isCurrent: true, isHover: true }" :tree-config="{}" :column-config="{ resizable: true }" :data="qiIndexSqlForm.qiIndexSqlSpecifyList" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow keep-source>

                                      <vxe-column field="leftParam" title="指定日期字段" tree-node :edit-render="{ autofocus: '.vxe-input--inner' }" width="200px" align="left">
                                        <template #edit="{ data, rowIndex }">
                                          <vxe-pulldown style="width: 100%; height: 100%" ref="pulldownRef" destroy-on-close transfer>
                                            <template #default>
                                              <vxe-input v-model="data.leftParam" placeholder="请选择字段" @focus="(value) => focusEvent(value, rowIndex)" @change="(row) => changeEvent(row, data, rowIndex, 'leftParam')"></vxe-input>
                                            </template>
                                            <template #dropdown>
                                              <vxe-table :row-config="{
                                                  isCurrent: true,
                                                  isHover: true,
                                                  keyField: 'id'
                                                }" class="mytable-scrollbar" height="300px" @current-change="(row) => tableFieldRowClick(row, data, rowIndex, 'leftParam')" border="inner" ref="tableRef" :column-config="{ resizable: true }" :show-header="false" :tree-config="{ transform: true, rowField: 'label', parentField: 'pLabel', expandAll: true }" :data="fieldListByTable">
                                                <vxe-column field="label" title="label" tree-node></vxe-column>
                                              </vxe-table>
                                            </template>
                                          </vxe-pulldown>
                                        </template>
                                      </vxe-column>
                                      <vxe-column field="rightParam" title="指定日期" width="200" :edit-render="{}">
                                        <template #edit="{ row, rowIndex, column }">
                                          <vxe-input v-model="row.rightParam" placeholder="请输入当前日期前的日期" type="text"></vxe-input>
                                        </template>
                                      </vxe-column>

                                      <vxe-column title="操作" fixed="right">
                                        <template #default="{ row }">
                                          <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="deleteSqlSpecify(row)" class="spanIcon"></vxe-button>
                                        </template>
                                      </vxe-column>
                                    </vxe-table>
                                  </div>
                                </el-tab-pane>
                              </el-tabs>
                            </Pane>
                            <Pane size="35">
                              <vxe-textarea v-model="sqlStrFullTxt" placeholder="sql语句" :autosize="{ minRows: 11, maxRows: 16 }"></vxe-textarea>
                            </Pane>
                            <Pane size="5">
                              <el-row :gutter="20">
                                <el-col :span="12">
                                  <el-form-item class="form-footer">
                                    <template #default>
                                      <el-button type="primary" :loading="sloading" @click="saveQiIndexSql('qiIndexSqlFormRef')">保存</el-button>
                                    </template>
                                  </el-form-item>
                                </el-col>
                              </el-row>
                            </Pane>
                          </Splitpanes>
                        </el-tab-pane>
                        <el-tab-pane v-for="item in qiIndexSqlForm.qiIndexSqlExistsList" :key="item.moduleType" :label="item.moduleName" :name="item.moduleType">
                          <Splitpanes>
                            <Pane size="30">
                              <div class="leftTable" style="height: 100%">
                                <vxe-table ref="feeitemVsItemdictTable" border class="mytable-scrollbar" height="auto" show-header-overflow show-overflow align="left" :row-config="{ isCurrent: true, isHover: true }" :data="qiIndexSqlBusinessList" :loading="showLoading" @cell-dblclick="deleteQiIndexSqlBusinessList">
                                  <vxe-column type="seq" title="序号" width="50"></vxe-column>
                                  <vxe-column field="businessValue" title="业务值"></vxe-column>
                                  <vxe-column field="businessNa" title="业务说明"></vxe-column>
                                </vxe-table>
                              </div>
                            </Pane>
                            <Pane size="70">
                              <vxe-toolbar perfect>
                                <template #buttons>
                                  <vxe-input v-model="searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getBusinessModuleAndData" @search-click="getBusinessModuleAndData()" @keyup="keyupEnter"></vxe-input>
                                  <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="getBusinessModuleAndData"></vxe-button>
                                </template>
                              </vxe-toolbar>
                              <vxe-table ref="detailTable" class="mytable-scrollbar" border align="center" height="auto" :data="tableDataList" @cell-dblclick="tableDataRowClick" :loading="tpLoading" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                                <vxe-column v-for="(item, index) in tableFieldList" :key="index" :field="item.columnName" :title="item.comments" :edit-render="{}"> </vxe-column>
                              </vxe-table>
                            </Pane>
                          </Splitpanes>
                        </el-tab-pane>
                      </el-tabs>
                    </Pane>
                  </Splitpanes>
                </Pane>
              </Splitpanes>
            </el-form>
          </el-main>
        </Pane>
      </Splitpanes>
    </el-container>
    <el-dialog title="数据源配置" :show-close="false" v-model="showDialog" append-to-body width="500px" :close-on-click-modal="false" destroy-on-close v-if="showDialog">
      <el-form ref="databaseFormRef" :model="databaseForm" :rules="databaseFormRule" label-width="120px" inline-message>
        <el-row :gutter='20'>
          <el-col :span='20'>
            <el-form-item prop="databaseCode" label="数据源编码">
              <el-input type="text" v-model="databaseForm.databaseCode" placeholder="请输入数据源编码" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter='20'>
          <el-col :span='20'>
            <el-form-item prop="databaseName" label="数据源名称">
              <el-input type="text" v-model="databaseForm.databaseName" placeholder="请输入数据源名称" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter='20'>
          <el-col :span='20'>
            <el-form-item prop="dbType" label="数据库类型">
              <el-select v-model="databaseForm.dbType" placeholder="请选择">
                <el-option v-for="item in dbMsList" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter='20'>
          <el-col :span='20'>
            <el-form-item prop="dbName" label="数据库名称">
              <el-input type="text" v-model="databaseForm.dbName" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter='20'>
          <el-col :span='20'>
            <el-form-item prop="dbUrl" label="数据库地址">
              <el-input type="text" v-model="databaseForm.dbUrl" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter='20'>
          <el-col :span='20'>
            <el-form-item prop="dbUser" label="登录帐户">
              <el-input type="text" v-model="databaseForm.dbUser" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter='20'>
          <el-col :span='20'>
            <el-form-item prop="dbPass" label="帐户密码">
              <el-input type="text" v-model="databaseForm.dbPass" placeholder="请输入" show-password></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter='20'>
          <el-col :span='20'>
            <el-form-item label="端口" prop="port">
              <el-input type="text" v-model="databaseForm.port" placeholder="端口" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter='20'>
          <el-col :span='20'>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="databaseForm.remark" :rows="6" type="textarea" placeholder="备注" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter='20'>
          <el-col :span='20'>
            <el-form-item prop="seq" label="序号">
              <el-input-number v-model="databaseForm.seq" :min="1" :max="1000" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item class="form-footer">
          <template #default>
            <el-button type="primary" :loading="saveLoading" @click="saveDatabase('databaseFormRef')">保存</el-button>
            <el-button type="primary" :loading="testConnectionLoading" @click="testConnection()">测试连接</el-button>
            <el-button @click="closeDialog('qcItemTableRef')">取消</el-button>

          </template>
        </el-form-item>

      </el-form>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted, computed } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { IsEmpty, formatDateTime } from '@/utils/common';
import { AppStore } from '@/stores/store';
let store = AppStore();
let qiIndexItem = null;
let qiIndex = null;
let sltMajorId = null;
let majorCode = ref(null);
let qiIndexMajorList: any = reactive([]);
let activeName = ref(null);
let activeSQLName = ref(null);
let activeTableName = ref('TABLE');
let functionTableRef = ref();
let joinSelectTable = ref();
let joinWhereTable = ref();
let joinSpecifyTable = ref();
let joinExistsTable = ref();
let joinOnTable = ref();
let qiDatabaseList: any = reactive([]);
let businessModuleList: any = reactive([]);
let tableFieldList: any = reactive([]); //设计模式表格数据
let tableDataList: any = reactive([]); //预览模式表格数据
let execloading = ref(false); //质控靶值树上的刷新
// 加载中 loading效果状态
let showLoading = ref(false); //刷新
let sloading = ref(false);
let sltSqlTable: any = reactive({});
let tpLoading = ref(false); //预览模式 刷新+表格
let showDialog = ref(false); //添加弹框展示状态
let saveLoading = ref(false); //表单保存状态
let testConnectionLoading = ref(false); //表单保存状态
let searchValue = ref('');
let pulldownRef = ref<VxePulldownInstance>();
let searchForm = reactive({
  executeTime: formatDateTime(new Date(), 'yyyy-MM-dd')
});
// 获取焦点事件
function focusEvent(value, rowindex) {
  const $pulldown = pulldownRef.value;
  if ($pulldown) {
    $pulldown.showPanel();
  }
}
// 输入框内容事件
function changeEvent({ value }, data, rowIndex, fildName) {
  data[rowIndex][fildName] = value;
  data[fildName] = value;
}
// 选中行
function tableFieldRowClick({ row }, data, rowIndex, fildName) {
  data[fildName] = row.value;
  data[rowIndex][fildName] = row.value;
  const $pulldown = pulldownRef.value;
  if ($pulldown) {
    $pulldown.hidePanel();
  }
}

//join条件
let databaseTableList: any = reactive([]);
let fieldListByTable: any = reactive([]);
// 右侧基本信息表单
let qiIndexSqlForm = reactive({
  id: null,
  indexId: '',
  indexCode: '',
  itemId: '',
  itemCode: '',
  majorId: '',
  majorCode: '',
  qiDatabaseId: '',
  sqlSentence: '',
  distinctFlag: false,
  orgId: '',
  qiIndexSqlTableList: [],
  qiIndexSqlSelectList: [],
  qiIndexSqlWhereList: [],
  qiIndexSqlExistsList: [],
  qiIndexSqlSpecifyList: []
});
let qiIndexSqlFormRule = {
  qiDatabaseId: [
    {
      required: true,
      message: '请输入项目编码',
      trigger: 'blur'
    }
  ],
  sqlSentence: [
    {
      required: true,
      message: '请输入项目编码',
      trigger: 'blur'
    }
  ]
};
//拼接sql
const sqlStrFullTxt = computed(() => {
  let r = 'SELECT  ';
  if (qiIndexSqlForm.distinctFlag) {
    r += 'DISTINCT ';
  }
  //拼接输出内容
  if (qiIndexSqlForm && qiIndexSqlForm.qiIndexSqlSelectList.length > 0) {
    for (let i = 0; i < qiIndexSqlForm.qiIndexSqlSelectList.length; i++) {
      const iterator = qiIndexSqlForm.qiIndexSqlSelectList[i];
      let isAggregation = false;
      let tableField = '';
      let tableName = '';
      let alias = '';
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'tableField') {
            if (!IsEmpty(iterator[key])) {
              tableField = iterator[key];
            }
          }
        }
      }
      if (qiIndexSqlForm && qiIndexSqlForm.qiIndexSqlTableList.length > 0) {
        for (const iterator of qiIndexSqlForm.qiIndexSqlTableList) {
          let isTrue = false;
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'tableName') {
                if (!IsEmpty(iterator[key]) && tableField.includes(iterator[key])) {
                  tableName = iterator[key];
                }
              }
            }
          }
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'alias') {
                if (!IsEmpty(iterator[key]) && !IsEmpty(tableName)) {
                  alias = iterator[key];
                  isTrue = true;
                  break;
                }
              }
            }
          }
          if (isTrue) {
            break;
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'aggregation') {
            if (!IsEmpty(iterator[key])) {
              isAggregation = true;
              r += iterator[key] + ' (';
            }
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'tableField') {
            if (!IsEmpty(alias)) {
              if (!IsEmpty(iterator[key]) && iterator[key].includes(tableName)) {
                r += iterator[key].replace(tableName, alias) + ' ';
              }
              if (isAggregation) {
                r += ') ';
              }
            } else {
              if (!IsEmpty(iterator[key])) {
                r += iterator[key] + ' ';
              }
              if (isAggregation) {
                r += ') ';
              }
            }
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'alias') {
            if (!IsEmpty(iterator[key])) {
              r += 'AS ' + iterator[key] + ',';
            }
          }
        }
      }
    }
  }
  if (qiIndexSqlForm && qiIndexSqlForm.qiIndexSqlSelectList.length > 0) {
    r = r.substring(0, r.length - 1);
  }
  //拼接表连接
  if (qiIndexSqlForm && qiIndexSqlForm.qiIndexSqlTableList.length > 0) {
    r += ' FROM ';
    for (let i = 0; i < qiIndexSqlForm.qiIndexSqlTableList.length; i++) {
      const iterator = qiIndexSqlForm.qiIndexSqlTableList[i];
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'joinType') {
            if (!IsEmpty(iterator[key])) {
              r += iterator[key] + ' ';
            } else {
              if (i != 0) {
                r += ' , ';
              }
            }
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'tableName') {
            if (!IsEmpty(iterator[key])) {
              r += iterator[key] + ' ';
            }
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'alias') {
            if (!IsEmpty(iterator[key])) {
              r += 'AS' + ' ' + iterator[key] + ' ';
            }
          }
        }
      }
      if (qiIndexSqlForm.qiIndexSqlTableList[i].qiIndexSqlOnList && qiIndexSqlForm.qiIndexSqlTableList[i].qiIndexSqlOnList.length > 0) {
        const onList = qiIndexSqlForm.qiIndexSqlTableList[i].qiIndexSqlOnList;
        for (let i = 0; i < onList.length; i++) {
          let leftParam = '';
          let rightParam = '';
          let leftTableName = '';
          let rightTableName = '';
          let leftAlias = '';
          let rightAlias = '';
          const iterator = onList[i];
          if (i == 0) {
            r += ' ON ';
          }
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'leftParam') {
                if (!IsEmpty(iterator[key])) {
                  leftParam = iterator[key];
                }
              }
            }
          }
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'rightParam') {
                if (!IsEmpty(iterator[key])) {
                  rightParam = iterator[key];
                }
              }
            }
          }
          if (qiIndexSqlForm && qiIndexSqlForm.qiIndexSqlTableList.length > 0) {
            for (const iterator of qiIndexSqlForm.qiIndexSqlTableList) {
              let isTrue = false;
              for (const key in iterator) {
                if (Object.prototype.hasOwnProperty.call(iterator, key)) {
                  if (key === 'tableName') {
                    if (!IsEmpty(iterator[key]) && leftParam.includes(iterator[key])) {
                      leftTableName = iterator[key];
                    }
                  }
                }
              }
              for (const key in iterator) {
                if (Object.prototype.hasOwnProperty.call(iterator, key)) {
                  if (key === 'alias') {
                    if (!IsEmpty(iterator[key]) && !IsEmpty(leftTableName)) {
                      leftAlias = iterator[key];
                      isTrue = true;
                      break;
                    }
                  }
                }
              }
              if (isTrue) {
                break;
              }
            }
            for (const iterator of qiIndexSqlForm.qiIndexSqlTableList) {
              let isTrue = false;
              for (const key in iterator) {
                if (Object.prototype.hasOwnProperty.call(iterator, key)) {
                  if (key === 'tableName') {
                    if (!IsEmpty(iterator[key]) && rightParam.includes(iterator[key])) {
                      rightTableName = iterator[key];
                    }
                  }
                }
              }
              for (const key in iterator) {
                if (Object.prototype.hasOwnProperty.call(iterator, key)) {
                  if (key === 'alias') {
                    if (!IsEmpty(iterator[key]) && !IsEmpty(rightTableName)) {
                      rightAlias = iterator[key];
                      isTrue = true;
                      break;
                    }
                  }
                }
              }
              if (isTrue) {
                break;
              }
            }
          }
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'leftBracket') {
                if (!IsEmpty(iterator[key])) {
                  r += iterator[key] + ' ';
                }
              }
            }
          }
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'leftParam') {
                if (!IsEmpty(leftAlias)) {
                  if (!IsEmpty(iterator[key]) && iterator[key].includes(leftTableName)) {
                    r += iterator[key].replace(leftTableName, leftAlias) + ' ';
                  }
                } else {
                  if (!IsEmpty(iterator[key])) {
                    r += iterator[key] + ' ';
                  }
                }
              }
            }
          }
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'symbol') {
                if (!IsEmpty(iterator[key])) {
                  r += iterator[key] + ' ';
                }
              }
            }
          }
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'rightParam') {
                if (!IsEmpty(rightAlias)) {
                  if (!IsEmpty(iterator[key]) && iterator[key].includes(rightTableName)) {
                    r += iterator[key].replace(rightTableName, rightAlias) + ' ';
                  }
                } else {
                  if (!IsEmpty(iterator[key])) {
                    r += iterator[key] + ' ';
                  }
                }
              }
            }
          }
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'rightBracket') {
                if (!IsEmpty(iterator[key])) {
                  r += iterator[key] + ' ';
                }
              }
            }
          }
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'relation') {
                if (!IsEmpty(iterator[key])) {
                  r += iterator[key] + ' ';
                }
              }
            }
          }
        }
      }
    }
  }
  r += ' WHERE ';
  r += ' 1=1 ';
  //拼接where
  if (qiIndexSqlForm && qiIndexSqlForm.qiIndexSqlWhereList.length > 0) {
    for (let i = 0; i < qiIndexSqlForm.qiIndexSqlWhereList.length; i++) {
      if (i == 0) {
        r += ' AND ';
      }
      let leftParam = '';
      let rightParam = '';
      let leftTableName = '';
      let rightTableName = '';
      let leftAlias = '';
      let rightAlias = '';

      const iterator = qiIndexSqlForm.qiIndexSqlWhereList[i];
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'leftParam') {
            if (!IsEmpty(iterator[key])) {
              leftParam = iterator[key];
            }
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'rightParam') {
            if (!IsEmpty(iterator[key])) {
              rightParam = iterator[key];
            }
          }
        }
      }
      if (qiIndexSqlForm && qiIndexSqlForm.qiIndexSqlTableList.length > 0) {
        for (const iterator of qiIndexSqlForm.qiIndexSqlTableList) {
          let isTrue = false;
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'tableName') {
                if (!IsEmpty(iterator[key]) && leftParam.includes(iterator[key])) {
                  leftTableName = iterator[key];
                }
              }
            }
          }
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'alias') {
                if (!IsEmpty(iterator[key]) && !IsEmpty(leftTableName)) {
                  leftAlias = iterator[key];
                  isTrue = true;
                  break;
                }
              }
            }
          }
          if (isTrue) {
            break;
          }
        }
        for (const iterator of qiIndexSqlForm.qiIndexSqlTableList) {
          let isTrue = false;
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'tableName') {
                if (!IsEmpty(iterator[key]) && rightParam.includes(iterator[key])) {
                  rightTableName = iterator[key];
                }
              }
            }
          }
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'alias') {
                if (!IsEmpty(iterator[key]) && !IsEmpty(rightTableName)) {
                  rightAlias = iterator[key];
                  isTrue = true;
                  break;
                }
              }
            }
          }
          if (isTrue) {
            break;
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'leftBracket') {
            if (!IsEmpty(iterator[key])) {
              r += iterator[key] + ' ';
            }
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'leftParam') {
            if (!IsEmpty(leftAlias)) {
              if (!IsEmpty(iterator[key]) && iterator[key].includes(leftTableName)) {
                r += iterator[key].replace(leftTableName, leftAlias) + ' ';
              }
            } else {
              if (!IsEmpty(iterator[key])) {
                r += iterator[key] + ' ';
              }
            }
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'symbol') {
            if (!IsEmpty(iterator[key])) {
              r += iterator[key] + ' ';
            }
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'rightParam') {
            if (!IsEmpty(rightAlias)) {
              if (!IsEmpty(iterator[key]) && iterator[key].includes(rightTableName)) {
                r += iterator[key].replace(rightTableName, rightAlias) + ' ';
              }
            } else {
              if (!IsEmpty(iterator[key])) {
                r += iterator[key] + ' ';
              }
            }
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'rightBracket') {
            if (!IsEmpty(iterator[key])) {
              r += iterator[key] + ' ';
            }
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'relation') {
            if (!IsEmpty(iterator[key])) {
              r += iterator[key] + ' ';
            }
          }
        }
      }
    }
  }
  //拼接Exists
  if (qiIndexSqlForm && qiIndexSqlForm.qiIndexSqlExistsList.length > 0) {
    for (let i = 0; i < qiIndexSqlForm.qiIndexSqlExistsList.length; i++) {
      const iterator = qiIndexSqlForm.qiIndexSqlExistsList[i];
      let isEmptyModuleType = false;
      let tableField = '';
      let tableName = '';
      let alias = '';
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'rightParam') {
            if (!IsEmpty(iterator[key])) {
              tableField = iterator[key];
            }
          }
        }
      }
      if (qiIndexSqlForm && qiIndexSqlForm.qiIndexSqlTableList.length > 0) {
        for (const iterator of qiIndexSqlForm.qiIndexSqlTableList) {
          let isTrue = false;
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'tableName') {
                if (!IsEmpty(iterator[key]) && tableField.includes(iterator[key])) {
                  tableName = iterator[key];
                }
              }
            }
          }
          for (const key in iterator) {
            if (Object.prototype.hasOwnProperty.call(iterator, key)) {
              if (key === 'alias') {
                if (!IsEmpty(iterator[key]) && !IsEmpty(tableName)) {
                  alias = iterator[key];
                  isTrue = true;
                  break;
                }
              }
            }
          }
          if (isTrue) {
            break;
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'moduleType') {
            if (!IsEmpty(iterator[key])) {
              isEmptyModuleType = true;
            }
          }
        }
      }
      if (!isEmptyModuleType) {
        continue;
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'relation') {
            if (!IsEmpty(iterator[key])) {
              r += iterator[key] + ' ';
            }
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'existsType') {
            if (!IsEmpty(iterator[key])) {
              r += iterator[key] + ' ';
            }
          }
        }
      }
      r += "( SELECT 1 FROM QI_INDEX_SQL_BUSINESS WHERE INDEX_CODE = '" + qiIndex.indexCode + "'" + " AND ITEM_CODE ='" + qiIndexItem.itemCode + "'" + " AND MAJOR_CODE ='" + majorCode.value + "'" + ' AND MODULE_TYPE =';
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'moduleType') {
            if (!IsEmpty(iterator[key])) {
              r += "'" + iterator[key] + "'" + ' ';
            }
          }
        }
      }
      for (const key in iterator) {
        if (Object.prototype.hasOwnProperty.call(iterator, key)) {
          if (key === 'rightParam') {
            if (!IsEmpty(alias)) {
              if (!IsEmpty(iterator[key]) && iterator[key].includes(tableName)) {
                r += ' AND  BUSINESS_VALUE = ' + iterator[key].replace(tableName, alias) + ')';
              }
            } else {
              if (!IsEmpty(iterator[key])) {
                r += iterator[key] + ')';
              }
            }
          }
        }
      }
    }
  }
  return r;
});

defineExpose({
  initPage
});

// 方法定义区 =============
function initPage(row: any, qiIndexRow: any) {
  qiIndexItem = row;
  qiIndex = qiIndexRow;
  getQiIndexMajorList();
}
onMounted(() => {
  getQiDatabaseList();
  getDictItemsList();
  getBusinessModuleList();
});
//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['dbMsType'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const dbMsType = dictTreeTypeItems.data.find((item) => item.code === 'dbMsType');
  dbMsList.push(...dbMsType.detailDataList);
}
// 新建父级菜单
async function handleTableAdd() {
  const $table = functionTableRef.value;
  if ($table) {
    $table.setAllRowExpand(true);
    // 获取新增的数据记录
    const record = {
      id: '',
      tableName: '', //表名
      alias: '', //别名
      joinType: '', //关联方式
      indexId: qiIndexItem.indexId,
      indexCode: qiIndex.indexCode,
      itemId: qiIndexItem.id,
      itemCode: qiIndexItem.itemCode,
      majorId: sltMajorId,
      majorCode: qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode,
      qiDatabaseId: qiIndexSqlForm.qiDatabaseId,
      qiSqlId: qiIndexSqlForm.id
    };
    qiIndexSqlForm.qiIndexSqlTableList.push(record);
    $table.loadData(qiIndexSqlForm.qiIndexSqlTableList);
    const { row: newRow } = await $table.insertAt(record, -1);
    // 设置编辑行
    await $table.setEditRow(record);
    /* if (row) {
      await $table.setTreeExpand(row, true); //新建一行空数据时展开这一栏
    }*/
  }
}

async function addJoinSelect() {
  const $table = joinSelectTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
    // 获取新增的数据记录
    const record = {
      id: '',
      tableField: '', //表名
      alias: '', //别名
      seq: 1, //关联方式
      indexId: qiIndexItem.indexId,
      indexCode: qiIndex.indexCode,
      itemId: qiIndexItem.id,
      itemCode: qiIndexItem.itemCode,
      majorId: sltMajorId,
      majorCode: qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode,
      qiDatabaseId: qiIndexSqlForm.qiDatabaseId,
      qiSqlId: qiIndexSqlForm.id
    };
    qiIndexSqlForm.qiIndexSqlSelectList.push(record);
    $table.loadData(qiIndexSqlForm.qiIndexSqlSelectList);
    const { row: newRow } = await $table.insertAt(record, -1);
    // 设置编辑行
    await $table.setEditRow(record);
    /* if (row) {
      await $table.setTreeExpand(row, true); //新建一行空数据时展开这一栏
    }*/
  }
}

// 添加join关联条件
async function addJoinWhere() {
  const $table = joinWhereTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
    // 获取新增的数据记录
    const record = {
      indexId: qiIndexItem.indexId,
      indexCode: qiIndex.indexCode,
      itemId: qiIndexItem.id,
      itemCode: qiIndexItem.itemCode,
      majorId: sltMajorId,
      majorCode: qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode,
      qiDatabaseId: qiIndexSqlForm.qiDatabaseId,
      qiSqlId: qiIndexSqlForm.id,
      leftBracket: '',
      leftParam: '', //左参数
      symbol: '', //符号
      rightParam: '', //右参数
      relation: '', //关系 and/or
      rightBracket: '', //右括号
      whereType: 'WHERE',
      seq: 1
    };
    qiIndexSqlForm.qiIndexSqlWhereList.push(record);
    $table.loadData(qiIndexSqlForm.qiIndexSqlWhereList);
    const { row: newRow } = await $table.insertAt(record, -1);
    // 设置编辑行
    await $table.setEditRow(record);
    /* if (row) {
      await $table.setTreeExpand(row, true); //新建一行空数据时展开这一栏
    }*/
  }
}

async function addJoinSpecify() {
  const $table = joinSpecifyTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
    // 获取新增的数据记录
    const record = {
      indexId: qiIndexItem.indexId,
      indexCode: qiIndex.indexCode,
      itemId: qiIndexItem.id,
      itemCode: qiIndexItem.itemCode,
      majorId: sltMajorId,
      majorCode: qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode,
      qiDatabaseId: qiIndexSqlForm.qiDatabaseId,
      qiSqlId: qiIndexSqlForm.id,
      leftBracket: '',
      leftParam: '', //左参数
      symbol: '', //符号
      rightParam: '', //右参数
      relation: '', //关系 and/or
      rightBracket: '', //右括号
      whereType: 'SPECIFY',
      seq: 1
    };
    qiIndexSqlForm.qiIndexSqlSpecifyList.push(record);
    $table.loadData(qiIndexSqlForm.qiIndexSqlSpecifyList);
    const { row: newRow } = await $table.insertAt(record, -1);
    // 设置编辑行
    await $table.setEditRow(record);
    /* if (row) {
      await $table.setTreeExpand(row, true); //新建一行空数据时展开这一栏
    }*/
  }
}

// 添加EXISTS关联条件
async function addJoinExists() {
  const $table = joinExistsTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
    // 获取新增的数据记录
    const record = {
      indexId: qiIndexItem.indexId,
      indexCode: qiIndex.indexCode,
      itemId: qiIndexItem.id,
      itemCode: qiIndexItem.itemCode,
      majorId: sltMajorId,
      majorCode: qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode,
      qiDatabaseId: qiIndexSqlForm.qiDatabaseId,
      qiSqlId: qiIndexSqlForm.id,
      relation: '',
      existsType: '', //左参数
      moduleType: '', //符号
      rightParam: '', //右参数
      seq: 1
    };
    qiIndexSqlForm.qiIndexSqlExistsList.push(record);
    $table.loadData(qiIndexSqlForm.qiIndexSqlExistsList);
    const { row: newRow } = await $table.insertAt(record, -1);
    // 设置编辑行
    await $table.setEditRow(record);
    /* if (row) {
      await $table.setTreeExpand(row, true); //新建一行空数据时展开这一栏
    }*/
  }
}

// 添加join关联条件
async function addJoinOn() {
  const $table = joinOnTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
    // 获取新增的数据记录
    const record = {
      indexId: qiIndexItem.indexId,
      indexCode: qiIndex.indexCode,
      itemId: qiIndexItem.id,
      itemCode: qiIndexItem.itemCode,
      majorId: sltMajorId,
      majorCode: qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode,
      qiDatabaseId: qiIndexSqlForm.qiDatabaseId,
      qiSqlId: qiIndexSqlForm.id,
      qiTableId: qiIndexSqlForm.qiIndexSqlTableList[curIndex.value].id,
      leftBracket: '',
      leftParam: '', //左参数
      symbol: '', //符号
      rightParam: '', //右参数
      relation: '', //关系 and/or
      rightBracket: '', //右括号
      whereType: 'ON',
      seq: IsEmpty(qiIndexSqlForm.qiIndexSqlTableList[curIndex.value].qiIndexSqlOnList) ? 1 : qiIndexSqlForm.qiIndexSqlTableList[curIndex.value].qiIndexSqlOnList.length + 1
    };

    if (IsEmpty(qiIndexSqlForm.qiIndexSqlTableList[curIndex.value].qiIndexSqlOnList)) {
      qiIndexSqlForm.qiIndexSqlTableList[curIndex.value].qiIndexSqlOnList = [];
    }

    qiIndexSqlForm.qiIndexSqlTableList[curIndex.value].qiIndexSqlOnList.push(record);
    $table.loadData(qiIndexSqlForm.qiIndexSqlTableList[curIndex.value].qiIndexSqlOnList);
    const { row: newRow } = await $table.insertAt(record, -1);
    // 设置编辑行
    await $table.setEditRow(record);
    /* if (row) {
      await $table.setTreeExpand(row, true); //新建一行空数据时展开这一栏
    }*/
  }
}

async function getQiDatabaseList() {
  qiDatabaseList.length = 0;
  const url = '/api/qi/qiDatabase/findQiDatabaseList';
  const qiDatabaseRes: any = await proxy.$http.get(url);
  qiDatabaseList.push(...qiDatabaseRes.data);
}

async function getBusinessModuleList() {
  const url = '/api/qi/qiIndexBusinessModule/findBusinessModules';
  const businessModules: any = await proxy.$http.get(url);
  businessModuleList.push(...businessModules.data);
}

// 获取专业信息
function getQiIndexMajorList() {
  qiIndexMajorList.length = 0; //放入数据前清空数据
  const url = '/api/qi/qiIndexMajor/getIndexMajorList/' + qiIndex.indexCode;
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (!IsEmpty(res.data) && res.data.length > 0) {
        qiIndexMajorList.push(...res.data);
        if (qiIndexMajorList && qiIndexMajorList.length > 0) {
          activeName.value = qiIndexMajorList[0].id;
          sltMajorId = qiIndexMajorList[0].id;
          majorCode.value = qiIndexMajorList[0].majorCode;
          findQiIndexSqlOne();
        }
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

function tabMajorClick(tab) {
  sltMajorId = tab.props.name;
  majorCode.value = qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode;
  findQiIndexSqlOne();
}
let curIndex = ref(-1);
// 点击设计模式表格当前行触发右侧表单变化
function tableRowClick({ row, rowIndex }: any) {
  if (!IsEmpty(rowIndex)) {
    curIndex.value = rowIndex;
  }
  if (IsEmpty(row)) {
    sltSqlTable = {};
  } else {
    (proxy.$refs.functionTableRef as any).setCurrentRow(row);
    sltSqlTable = row;
  }
}

function tabSQLClick(tab) {
  console.log(tab);
}

//装饰器中的参数是方法名，用来传递给父组件
function tableNameChange({ row }) {
  //获取对应表的字段
  getFieldByTable();
}

function saveQiIndexSql(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    sloading.value = true;
    if (qiIndexSqlForm.id === null) {
      const url = '/api/qi/qiIndexSql/addQiIndexSql';
      const supplier = {
        indexId: qiIndexItem.indexId,
        indexCode: qiIndex.indexCode,
        itemId: qiIndexItem.id,
        itemCode: qiIndexItem.itemCode,
        majorId: sltMajorId,
        majorCode: qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode,
        qiDatabaseId: qiIndexSqlForm.qiDatabaseId,
        sqlSentence: sqlStrFullTxt.value,
        distinctFlag: qiIndexSqlForm.distinctFlag,
        orgId: store.userInfo.orgId,
        qiIndexSqlTableList: qiIndexSqlForm.qiIndexSqlTableList,
        qiIndexSqlSelectList: qiIndexSqlForm.qiIndexSqlSelectList,
        qiIndexSqlWhereList: qiIndexSqlForm.qiIndexSqlWhereList,
        qiIndexSqlExistsList: qiIndexSqlForm.qiIndexSqlExistsList,
        qiIndexSqlSpecifyList: qiIndexSqlForm.qiIndexSqlSpecifyList
      };
      proxy.$http
        .post(url, supplier)
        .then((res: any) => {
          VxeMessage('新增成功', VxeNotifyType.success);
          sloading.value = false;
          findQiIndexSqlOne();
        })
        .catch((err: any) => {
          sloading.value = false;
          console.log(err);

          VxeMessage('新增失败', VxeNotifyType.error);
        });
    } else {
      // 修改用户
      const url = '/api/qi/qiIndexSql/updateQiIndexSql';
      const supplier = {
        id: qiIndexSqlForm.id,
        indexId: qiIndexSqlForm.indexId,
        indexCode: qiIndexSqlForm.indexCode,
        itemId: qiIndexSqlForm.itemId,
        itemCode: qiIndexSqlForm.itemCode,
        majorId: qiIndexSqlForm.majorId,
        majorCode: qiIndexSqlForm.majorCode,
        qiDatabaseId: qiIndexSqlForm.qiDatabaseId,
        sqlSentence: sqlStrFullTxt.value,
        distinctFlag: qiIndexSqlForm.distinctFlag,
        orgId: qiIndexSqlForm.orgId,
        qiIndexSqlTableList: qiIndexSqlForm.qiIndexSqlTableList,
        qiIndexSqlSelectList: qiIndexSqlForm.qiIndexSqlSelectList,
        qiIndexSqlWhereList: qiIndexSqlForm.qiIndexSqlWhereList,
        qiIndexSqlExistsList: qiIndexSqlForm.qiIndexSqlExistsList,
        qiIndexSqlSpecifyList: qiIndexSqlForm.qiIndexSqlSpecifyList
      };
      proxy.$http
        .post(url, supplier)
        .then((res: any) => {
          sloading.value = false;
          VxeMessage('修改成功', VxeNotifyType.success);
          findQiIndexSqlOne();
        })
        .catch((err: any) => {
          sloading.value = false;
          VxeMessage('修改失败', VxeNotifyType.error);
        });
    }
  });
}

function handleQiIndexSqlDelete() {
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        const url = '/api/qi/qiIndexSql/deleteQiIndexSql';
        proxy.$http
          .post(url, qiIndexSqlForm)
          .then((res: any) => {
            findQiIndexSqlOne();
          })
          .catch((err) => {
            VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
          });
      }
    });
}

// 获取列表
function findQiIndexSqlOne() {
  activeTableName.value = 'TABLE';
  const url = '/api/qi/qiIndexSql/findQiIndexSqlOne';
  proxy.$http
    .get(url, {
      params: {
        indexCode: qiIndex.indexCode,
        itemCode: qiIndexItem.itemCode,
        majorCode: majorCode.value
      }
    })
    .then((res: any) => {
      if (res.status.code === 1) {
        if (!IsEmpty(res.data)) {
          setQiIndexSqlForm(res.data);
        } else {
          clearQiIndexSqlForm();
        }
        activeSQLName.value = 'SELECT';
      } else {
        VxeMessage('获取列表失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
// 获取表列表
function getDatabaseGetTableist() {
  databaseTableList.length = 0;
  if (IsEmpty(qiIndexSqlForm.qiDatabaseId)) {
    return;
  }
  const url = '/api/qi/qiDatabase/qiDatabaseGetTables';
  proxy.$http
    .get(url, { params: { qiDatabaseId: qiIndexSqlForm.qiDatabaseId } })
    .then((res: any) => {
      if (res.status.code === 1) {
        databaseTableList.push(...res.data);
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

//通过表获取所有字段
function getFieldByTable() {
  fieldListByTable.length = 0;
  if (IsEmpty(qiIndexSqlForm.qiDatabaseId) || IsEmpty(qiIndexSqlForm.qiIndexSqlTableList)) {
    return;
  }
  const tables = [];
  for (const item of qiIndexSqlForm.qiIndexSqlTableList) {
    if (IsEmpty(item.tableName)) {
      continue;
    }
    tables.push(item.tableName);
  }
  if (IsEmpty(tables)) {
    return;
  }
  const data = {
    id: qiIndexSqlForm.qiDatabaseId,
    tables: tables
  };
  const url = '/api/qi/qiDatabase/getQiDatabaseTableFieldList';
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      fieldListByTable.push(...res.data);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

function setQiIndexSqlForm(row: any) {
  qiIndexSqlForm.id = row.id;
  qiIndexSqlForm.indexId = row.indexId;
  qiIndexSqlForm.indexCode = row.indexCode;
  qiIndexSqlForm.itemId = row.itemId;
  qiIndexSqlForm.itemCode = row.itemCode;
  qiIndexSqlForm.majorId = row.majorId;
  qiIndexSqlForm.majorCode = row.majorCode;
  qiIndexSqlForm.qiDatabaseId = row.qiDatabaseId;
  qiIndexSqlForm.sqlSentence = row.sqlSentence;
  qiIndexSqlForm.distinctFlag = row.distinctFlag;
  qiIndexSqlForm.orgId = row.orgId;
  qiIndexSqlForm.qiIndexSqlTableList = row.qiIndexSqlTableList;
  if (!IsEmpty(qiIndexSqlForm.qiDatabaseId)) {
    getDatabaseGetTableist();
    if (!IsEmpty(qiIndexSqlForm.qiIndexSqlTableList) && qiIndexSqlForm.qiIndexSqlTableList.length > 0) {
      getFieldByTable();
    } else {
      fieldListByTable.length = 0;
    }
  }
  const kn = qiIndexSqlForm.qiIndexSqlTableList.find((k) => k.id == sltSqlTable.id);
  if (IsEmpty(kn)) {
    tableRowClick({ row: qiIndexSqlForm.qiIndexSqlTableList[0], rowIndex: 0 }); //默认选中第一条数据
  } else {
    tableRowClick({ row: kn }); //默认选中第一条数据
  }
  qiIndexSqlForm.qiIndexSqlSelectList = row.qiIndexSqlSelectList;
  qiIndexSqlForm.qiIndexSqlWhereList = row.qiIndexSqlWhereList;
  qiIndexSqlForm.qiIndexSqlSpecifyList = row.qiIndexSqlSpecifyList;
  qiIndexSqlForm.qiIndexSqlExistsList = row.qiIndexSqlExistsList;
  if (!IsEmpty(qiIndexSqlForm.qiIndexSqlExistsList) && qiIndexSqlForm.qiIndexSqlExistsList.length > 0) {
    for (let sqlExObj of qiIndexSqlForm.qiIndexSqlExistsList) {
      sqlExObj.moduleName = businessModuleList.find((m) => m.moduleType == sqlExObj.moduleType).moduleName;
    }
  }
}

let sltBusinessModule = null;
let sltModuleType = null;
function tabHandleClick(tab) {
  if (tab.index >= 1) {
    sltModuleType = tab.props.name;
    getBusinessModuleAndData();
    getQiIndexSqlBusinessList();
  }
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    getBusinessModuleAndData();
  }
}
function getBusinessModuleAndData() {
  //根据moduleType 查出表 及表数据
  tableFieldList.length = 0;
  tableDataList.length = 0;
  tpLoading.value = true;
  sltBusinessModule = businessModuleList.find((m) => m.moduleType == sltModuleType);
  const url = '/api/qi/qiIndexBusinessModule/getBusinessModuleAndData';
  proxy.$http
    .get(url, {
      params: {
        indexCode: qiIndex.indexCode,
        itemCode: qiIndexItem.itemCode,
        majorCode: majorCode.value,
        moduleType: sltModuleType,
        keywords: searchValue.value
      }
    })
    .then((res: any) => {
      if (res.status.code === 1) {
        tableFieldList.push(...res.data.tableFieldList);
        tableDataList.push(...res.data.tableDataList);
      } else {
        VxeMessage('获取列表失败', VxeNotifyType.error);
      }
      tpLoading.value = false;
    })
    .catch((err: any) => {
      tpLoading.value = false;
      VxeMessage(err, VxeNotifyType.error);
    });
}
let qiIndexSqlBusinessList = reactive([]);
function getQiIndexSqlBusinessList() {
  qiIndexSqlBusinessList.length = 0;
  const url = '/api/qi/qiIndexSqlBusiness/findQiIndexSqlBusinessList';
  const data = {
    params: {
      indexCode: qiIndex.indexCode,
      itemCode: qiIndexItem.itemCode,
      majorCode: majorCode.value,
      moduleType: sltModuleType
    }
  };
  proxy.$http
    .get(url, data)
    .then((res: any) => {
      qiIndexSqlBusinessList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 双击中间列表删除数据
function deleteQiIndexSqlBusinessList({ row }: any) {
  const url = '/api/qi/qiIndexSqlBusiness/deleteQiIndexSqlBusiness';
  proxy.$http
    .post(url, row)
    .then((res: any) => {
      getQiIndexSqlBusinessList();
      getBusinessModuleAndData();
      VxeMessage(res.status.msg, VxeNotifyType.success);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

function tableDataRowClick({ row }: any) {
  const url = '/api/qi/qiIndexSqlBusiness/addQiIndexSqlBusiness';
  let labFeeitemVsItemDict = {
    businessValue: row[sltBusinessModule.outField],
    businessNa: row[sltBusinessModule.showField],
    moduleType: sltBusinessModule.moduleType,
    indexId: qiIndexItem.indexId,
    indexCode: qiIndex.indexCode,
    itemId: qiIndexItem.id,
    itemCode: qiIndexItem.itemCode,
    majorId: sltMajorId,
    majorCode: qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode
  };
  proxy.$http
    .post(url, labFeeitemVsItemDict)
    .then((res: any) => {
      getQiIndexSqlBusinessList();
      getBusinessModuleAndData();
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

function deleteSqlTable(row: any) {
  proxy
    .$confirm('确定删除？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const index = qiIndexSqlForm.qiIndexSqlTableList.findIndex((item) => item == row);
      qiIndexSqlForm.qiIndexSqlTableList.splice(index, 1);
      getFieldByTable();
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function deleteSqlSelect(row: any) {
  proxy
    .$confirm('确定删除？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const index = qiIndexSqlForm.qiIndexSqlSelectList.findIndex((item) => item == row);
      qiIndexSqlForm.qiIndexSqlSelectList.splice(index, 1);
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function deleteSqlWhere(row: any) {
  proxy
    .$confirm('确定删除？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const index = qiIndexSqlForm.qiIndexSqlWhereList.findIndex((item) => item == row);
      qiIndexSqlForm.qiIndexSqlWhereList.splice(index, 1);
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function deleteSqlSpecify(row: any) {
  proxy
    .$confirm('确定删除？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const index = qiIndexSqlForm.qiIndexSqlSpecifyList.findIndex((item) => item == row);
      qiIndexSqlForm.qiIndexSqlSpecifyList.splice(index, 1);
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function deleteSqlExists(row: any) {
  proxy
    .$confirm('确定删除？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const index = qiIndexSqlForm.qiIndexSqlExistsList.findIndex((item) => item == row);
      qiIndexSqlForm.qiIndexSqlExistsList.splice(index, 1);
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function deleteSqlOn(row: any) {
  proxy
    .$confirm('确定删除？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const index = qiIndexSqlForm.qiIndexSqlTableList[curIndex.value].qiIndexSqlOnList.findIndex((item) => item == row);
      qiIndexSqlForm.qiIndexSqlTableList[curIndex.value].qiIndexSqlOnList.splice(index, 1);
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

// 清空中间规则弹框表单
async function clearQiIndexSqlForm() {
  qiIndexSqlForm.id = null;
  qiIndexSqlForm.indexId = '';
  qiIndexSqlForm.itemId = '';
  qiIndexSqlForm.majorId = '';
  qiIndexSqlForm.indexCode = '';
  qiIndexSqlForm.itemCode = '';
  qiIndexSqlForm.majorCode = '';
  qiIndexSqlForm.qiDatabaseId = '';
  qiIndexSqlForm.sqlSentence = '';
  qiIndexSqlForm.distinctFlag = false;
  qiIndexSqlForm.orgId = '';
  qiIndexSqlForm.qiIndexSqlTableList.length = 0;
  qiIndexSqlForm.qiIndexSqlSelectList.length = 0;
  qiIndexSqlForm.qiIndexSqlWhereList.length = 0;
  qiIndexSqlForm.qiIndexSqlExistsList.length = 0;
  qiIndexSqlForm.qiIndexSqlSpecifyList.length = 0;
  fieldListByTable.length = 0;
  databaseTableList.length = 0;
  const $table = joinSelectTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
    //默认塞三条数据
    let defaultList = [
      {
        alias: 'dataNo',
        indexId: qiIndexItem.indexId,
        indexCode: qiIndex.indexCode,
        itemId: qiIndexItem.id,
        itemCode: qiIndexItem.itemCode,
        majorId: sltMajorId,
        majorCode: majorCode.value,
        tableField: ''
      },
      {
        alias: 'operateDate',
        indexId: qiIndexItem.indexId,
        indexCode: qiIndex.indexCode,
        itemId: qiIndexItem.id,
        itemCode: qiIndexItem.itemCode,
        majorId: sltMajorId,
        majorCode: majorCode.value,
        tableField: ''
      },
      {
        alias: 'quantity',
        indexId: qiIndexItem.indexId,
        indexCode: qiIndex.indexCode,
        itemId: qiIndexItem.id,
        itemCode: qiIndexItem.itemCode,
        majorId: sltMajorId,
        majorCode: majorCode.value,
        tableField: ''
      }
    ];
    qiIndexSqlForm.qiIndexSqlSelectList.push(...defaultList);
    $table.loadData(qiIndexSqlForm.qiIndexSqlSelectList);
  }
}

function databaseChangeEvent() {
  getDatabaseGetTableist();
}

function getBusinessModuleDes(row) {
  return businessModuleList.find((m) => m.moduleType == row.moduleType) ? businessModuleList.find((m) => m.moduleType == row.moduleType).moduleName : '';
}

let joinList = reactive([
  {
    value: 'LEFT JOIN',
    name: '左连接'
  },
  {
    value: 'RIGHT JOIN',
    name: '右连接'
  },
  {
    value: 'INNER JOIN',
    name: '内连接'
  }
]);
let symbolList = reactive([
  {
    value: '='
  },
  {
    value: '<>'
  },
  {
    value: '>'
  },
  {
    value: '<'
  },
  {
    value: '>='
  },
  {
    value: '<='
  },
  {
    value: 'like'
  },
  {
    value: 'not like'
  },
  {
    value: 'is'
  }
]);
let relationList = reactive([
  {
    value: 'and'
  },
  {
    value: 'or'
  }
]);

let existsTypeOBJList = reactive([
  {
    value: 'EXISTS'
  },
  {
    value: 'NOT EXISTS'
  }
]);
let aggregationList = reactive([
  {
    value: 'SUM'
  },
  {
    value: 'MAX'
  },
  {
    value: 'MIN'
  },
  {
    value: 'AVG'
  },
  {
    value: 'COUNT'
  }
]);

let databaseForm = reactive({
  id: null,
  databaseName: '',
  databaseCode: '',
  dbType: '',
  dbName: '',
  dbUrl: '',
  port: '',
  dbUser: '',
  dbPass: '',
  remark: '',
  seq: 1,
  orgId: ''
});

let databaseFormRule = {
  databaseCode: [
    {
      required: true,
      message: '请输入编码',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ],
  databaseName: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    }
  ]
};

function addQiDatabaseModal() {
  showDialog.value = true; //添加弹框展示状态
}

function saveDatabase(formName: any) {
  let $el = proxy.$refs[formName];

  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    saveLoading.value = true;

    let url = '';
    let objData = {
      id: databaseForm.id,
      databaseName: databaseForm.databaseName,
      databaseCode: databaseForm.databaseCode,
      dbType: databaseForm.dbType,
      dbName: databaseForm.dbName,
      dbUrl: databaseForm.dbUrl,
      port: databaseForm.port,
      dbUser: databaseForm.dbUser,
      dbPass: databaseForm.dbPass,
      remark: databaseForm.remark,
      seq: databaseForm.seq,
      orgId: IsEmpty(databaseForm.orgId) ? store.userInfo.orgId : databaseForm.orgId
    };
    if (databaseForm.id == null) {
      url = '/api/qi/qiDatabase/addDatabase';
    } else {
      url = '/api/qi/qiDatabase/editDatabase';
    }

    proxy.$http
      .post(url, objData)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('保存成功', VxeNotifyType.success);
          closeDialog();
          qiIndexSqlForm.qiDatabaseId = res.data.id;
          getQiDatabaseList();
        } else {
          VxeMessage('保存失败1', VxeNotifyType.error);
        }
        saveLoading.value = false;
      })
      .catch((err: any) => {
        saveLoading.value = false;
        VxeMessage('保存失败2', VxeNotifyType.error);
      });
  });
}

// 弹框取消按钮
function closeDialog() {
  clearForm();
  showDialog.value = false;
}

function clearForm() {
  databaseForm.id = null;
  databaseForm.databaseName = '';
  databaseForm.databaseCode = '';
  databaseForm.dbType = '';
  databaseForm.dbName = '';
  databaseForm.dbUrl = '';
  databaseForm.port = '';
  databaseForm.dbUser = '';
  databaseForm.dbPass = '';
  databaseForm.remark = '';

  databaseForm.seq = qiDatabaseList.length + 1;
  databaseForm.orgId = '';
}
let dbMsList: any = reactive([]); //选择字典

// 测试数据库连接
function testConnection() {
  testConnectionLoading.value = true;
  let url = '/api/qi/qiDatabase/qiDatabaseConnection';
  const el: any = proxy.$refs.databaseFormRef;
  if (!el) return;
  el.validate((valid: any) => {
    if (!valid) {
      testConnectionLoading.value = false;
      return false;
    }
    proxy.$http
      .post(url, databaseForm)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage(res.status.msg, VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
        testConnectionLoading.value = false;
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
        testConnectionLoading.value = false;
      });
  });
}

let copyQiIndexSql: any = ref({});

//复制
function copyQiIndexSqlClick() {
  copyQiIndexSql.value = JSON.parse(JSON.stringify(qiIndexSqlForm));
}
//粘贴
function pasteQiIndexSqlClick() {
  qiIndexSqlForm.qiDatabaseId = copyQiIndexSql.value.qiDatabaseId;
  getDatabaseGetTableist();
  qiIndexSqlForm.distinctFlag = copyQiIndexSql.value.distinctFlag;
  //table
  qiIndexSqlForm.qiIndexSqlTableList.length = 0;
  if (copyQiIndexSql.value.qiIndexSqlTableList.length > 0) {
    for (const pasteTable of copyQiIndexSql.value.qiIndexSqlTableList) {
      const record = {
        id: '',
        tableName: pasteTable.tableName, //表名
        alias: pasteTable.alias, //别名
        joinType: pasteTable.joinType, //关联方式
        indexId: qiIndexItem.indexId,
        indexCode: qiIndex.indexCode,
        itemId: qiIndexItem.id,
        itemCode: qiIndexItem.itemCode,
        majorId: sltMajorId,
        majorCode: qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode,
        qiDatabaseId: qiIndexSqlForm.qiDatabaseId,
        qiSqlId: qiIndexSqlForm.id
      };
      qiIndexSqlForm.qiIndexSqlTableList.push(record);
    }
  }
  //SELECT
  qiIndexSqlForm.qiIndexSqlSelectList.length = 0;
  if (copyQiIndexSql.value.qiIndexSqlSelectList.length > 0) {
    for (const pasteSelect of copyQiIndexSql.value.qiIndexSqlSelectList) {
      const record = {
        id: '',
        tableField: pasteSelect.tableField, //表名
        alias: pasteSelect.alias, //别名
        aggregation: pasteSelect.aggregation,
        seq: qiIndexSqlForm.qiIndexSqlSelectList.length, //关联方式
        indexId: qiIndexItem.indexId,
        indexCode: qiIndex.indexCode,
        itemId: qiIndexItem.id,
        itemCode: qiIndexItem.itemCode,
        majorId: sltMajorId,
        majorCode: qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode,
        qiDatabaseId: qiIndexSqlForm.qiDatabaseId,
        qiSqlId: qiIndexSqlForm.id
      };
      qiIndexSqlForm.qiIndexSqlSelectList.push(record);
    }
    const $table = joinSelectTable.value;
    if ($table) {
      $table.loadData(qiIndexSqlForm.qiIndexSqlSelectList);
    }
  }
  //WHERE
  qiIndexSqlForm.qiIndexSqlWhereList.length = 0;
  if (copyQiIndexSql.value.qiIndexSqlWhereList.length > 0) {
    for (const pasteWhere of copyQiIndexSql.value.qiIndexSqlWhereList) {
      const record = {
        indexId: qiIndexItem.indexId,
        indexCode: qiIndex.indexCode,
        itemId: qiIndexItem.id,
        itemCode: qiIndexItem.itemCode,
        majorId: sltMajorId,
        majorCode: qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode,
        qiDatabaseId: qiIndexSqlForm.qiDatabaseId,
        qiSqlId: qiIndexSqlForm.id,
        leftBracket: pasteWhere.leftBracket,
        leftParam: pasteWhere.leftParam, //左参数
        symbol: pasteWhere.symbol, //符号
        rightParam: pasteWhere.rightParam, //右参数
        relation: pasteWhere.relation, //关系 and/or
        rightBracket: pasteWhere.rightBracket, //右括号
        whereType: 'WHERE',
        seq: qiIndexSqlForm.qiIndexSqlWhereList.length + 1
      };
      qiIndexSqlForm.qiIndexSqlWhereList.push(record);
    }
    const $table = joinWhereTable.value;
    if ($table) {
      $table.loadData(qiIndexSqlForm.qiIndexSqlWhereList);
    }
  }
  //Specify
  qiIndexSqlForm.qiIndexSqlSpecifyList.length = 0;
  if (copyQiIndexSql.value.qiIndexSqlSpecifyList.length > 0) {
    for (const pasteSpecify of copyQiIndexSql.value.qiIndexSqlSpecifyList) {
      const record = {
        indexId: qiIndexItem.indexId,
        indexCode: qiIndex.indexCode,
        itemId: qiIndexItem.id,
        itemCode: qiIndexItem.itemCode,
        majorId: sltMajorId,
        majorCode: qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode,
        qiDatabaseId: qiIndexSqlForm.qiDatabaseId,
        qiSqlId: qiIndexSqlForm.id,
        leftBracket: pasteSpecify.leftBracket,
        leftParam: pasteSpecify.leftParam, //左参数
        symbol: pasteSpecify.symbol, //符号
        rightParam: pasteSpecify.rightParam, //右参数
        relation: pasteSpecify.relation, //关系 and/or
        rightBracket: pasteSpecify.rightBracket, //右括号
        whereType: 'SPECIFY',
        seq: qiIndexSqlForm.qiIndexSqlSpecifyList.length + 1
      };
      qiIndexSqlForm.qiIndexSqlSpecifyList.push(record);
    }
    const $table = joinSpecifyTable.value;
    if ($table) {
      $table.loadData(qiIndexSqlForm.qiIndexSqlSpecifyList);
    }
  }

  //Exists
  qiIndexSqlForm.qiIndexSqlExistsList.length = 0;
  if (copyQiIndexSql.value.qiIndexSqlExistsList.length > 0) {
    for (const pasteExists of copyQiIndexSql.value.qiIndexSqlExistsList) {
      const record = {
        indexId: qiIndexItem.indexId,
        indexCode: qiIndex.indexCode,
        itemId: qiIndexItem.id,
        itemCode: qiIndexItem.itemCode,
        majorId: sltMajorId,
        majorCode: qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode,
        qiDatabaseId: qiIndexSqlForm.qiDatabaseId,
        qiSqlId: qiIndexSqlForm.id,
        relation: pasteExists.relation,
        existsType: pasteExists.existsType, //左参数
        moduleType: pasteExists.moduleType, //符号
        rightParam: pasteExists.rightParam, //右参数
        seq: qiIndexSqlForm.qiIndexSqlExistsList.length + 1
      };
      qiIndexSqlForm.qiIndexSqlExistsList.push(record);
    }
    const $table = joinExistsTable.value;
    if ($table) {
      $table.loadData(qiIndexSqlForm.qiIndexSqlExistsList);
    }
  }
  //ON
  if (qiIndexSqlForm.qiIndexSqlTableList.length > 0) {
    for (let i = 0; i < qiIndexSqlForm.qiIndexSqlTableList.length; i++) {
      let qiSqlTable = qiIndexSqlForm.qiIndexSqlTableList[i];
      const qiSqlOnList = copyQiIndexSql.value.qiIndexSqlTableList[i].qiIndexSqlOnList;
      if (qiSqlOnList && qiSqlOnList.length > 0) {
        for (const qiOn of qiSqlOnList) {
          const record = {
            indexId: qiIndexItem.indexId,
            indexCode: qiIndex.indexCode,
            itemId: qiIndexItem.id,
            itemCode: qiIndexItem.itemCode,
            majorId: sltMajorId,
            majorCode: qiIndexMajorList.find((m) => m.id == sltMajorId).majorCode,
            qiDatabaseId: qiIndexSqlForm.qiDatabaseId,
            qiSqlId: qiIndexSqlForm.id,
            qiTableId: qiSqlTable.id,
            leftBracket: qiOn.leftBracket,
            leftParam: qiOn.leftParam, //左参数
            symbol: qiOn.symbol, //符号
            rightParam: qiOn.rightParam, //右参数
            relation: qiOn.relation, //关系 and/or
            rightBracket: qiOn.rightBracket, //右括号
            whereType: 'ON',
            seq: IsEmpty(qiSqlTable.qiIndexSqlOnList) ? 1 : qiSqlTable.qiIndexSqlOnList.length + 1
          };
          if (IsEmpty(qiSqlTable.qiIndexSqlOnList)) {
            qiSqlTable.qiIndexSqlOnList = [];
          }
          qiSqlTable.qiIndexSqlOnList.push(record);
        }
        const $table = joinOnTable.value;
        if ($table) {
          $table.loadData(qiSqlTable.qiIndexSqlOnList);
        }
      }
    }
  }
}

//立即执行
function executeImmediatelyClick() {
  execloading.value = true;
  const url = '/api/qi/qiIndexSqlData/executeImmediatelyData';
  const data = {
    params: {
      indexId: qiIndexItem.indexId,
      itemId: qiIndexItem.id,
      majorId: sltMajorId,
      executeTime: searchForm.executeTime
    }
  };
  proxy.$http
    .get(url, data)
    .then((res: any) => {
      if (res.status.code !== 1 && res.status.code !== 200) {
        VxeMessage('执行失败', VxeNotifyType.error);
      } else {
        VxeMessage('执行成功', VxeNotifyType.success);
      }
      execloading.value = false;
    })
    .catch((err: any) => {
      execloading.value = false;
      proxy.$alert(err, '提示');
    });
}
</script>

<style lang="scss" scoped>
#qiItemSetDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .tablebox {
    height: calc(100% - 40px);
  }

  .el-aside {
    background-color: #f1f1f100 !important;
    color: #f7f9fc;
    .leftTabs {
      width: 100%;
      :deep(.el-tabs__header) {
        width: 100%;
        margin-right: 0;
        .el-tabs__nav {
          width: 100%;
          .el-tabs__item {
            display: flex;
            align-items: center;
            justify-content: flex-start;
          }
        }
      }
    }
  }
  .horizontalLine {
    :deep(.splitpanes__splitter) {
      background-color: $base-white;
    }
  }
  .toolbartitle1 {
    font-weight: bold;
    height: 10px;
    line-height: 10px;
    padding-left: 10px;
  }
  .toolbartitle2 {
    margin: 0px 5px 0px 0px;
  }
  .toolbartitle3 {
    margin: 0px 5px 0px 5px;
  }
  .elTabsFour {
    height: calc(100% - 2px);
    :deep(.el-tabs__content) {
      height: calc(100% - 39px);
    }
  }
  :deep(.leftTabs .el-tabs__item.is-active) {
    color: #ff0000 !important;
    background-color: #89d7fc !important;
  }
  :deep(.el-tabs__item:hover) {
    color: #ff6666;
  }
}
</style>
